<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.blurry"
          clearable
          size="small"
          placeholder="输入文章名称或咨询者手机号搜索"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <date-range-picker v-model="query.createTime" class="date-item" unlink-panels />
        <el-select
          v-model="query.state"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 90px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-select
          v-if="query.state === 3 || !query.state"
          v-model="query.subState"
          clearable
          size="small"
          placeholder="追问状态"
          class="filter-item"
          style="width: 120px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in enabledSubStateOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-select
          v-model="query.type"
          clearable
          size="small"
          placeholder="类型"
          class="filter-item"
          style="width: 90px"
          @change="crud.toQuery"
        >
          <el-option v-for="item in typeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <rrOperation />
      </div>
      <crudOperation :permission="permission">
        <el-button
          v-if="crud.optShow.dist"
          slot="left"
          v-permission="permission.dist"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          :disabled="crud.selections.length === 0"
          @click="toDistribute(crud.selections)"
        >
          分配
        </el-button>
      </crudOperation>
    </div>
    <!-- 表单渲染 -->
    <el-dialog append-to-body :close-on-click-modal="false" :visible.sync="distributing" :title="'分配咨询'" width="520px">
      <el-form ref="form" :inline="true" :model="userForm" size="small" label-width="80px">
        <el-form-item label="客服会员" prop="name">
          <el-select
            v-model="userForm.id"
            style="width: 380px;"
            filterable
            remote
            reserve-keyword
            placeholder="请输入客服会员用户名"
            :remote-method="getClientUsers"
            :loading="loading"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="推送消息" prop="pushMessage">
          <el-switch
            v-model="userForm.pushMessage"
            active-color="#409EFF"
            inactive-color="#F56C6C"
          />
        </el-form-item>
        <el-form-item label="发送短信" prop="sendMessage">
          <el-switch
            v-model="userForm.sendMessage"
            active-color="#409EFF"
            inactive-color="#F56C6C"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="distributing=false">取消</el-button>
        <el-button type="primary" @click="confirmDistribute">确认</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      lazy
      :load="getArticleDatas"
      :data="crud.data"
      row-key="id"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="名称" prop="queryContent">
        <template slot-scope="scope">
          <div>
            <span style="max-width: 10em;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">{{ scope.row.queryContent }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="咨询者" prop="user">
        <template slot-scope="scope">
          <span>{{ scope.row.user ? scope.row.user.username : '-' }}{{ scope.row.user && scope.row.user.userLevel > 0 ? '(VIP)' : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回答者" prop="answerUser">
        <template slot-scope="scope">
          <span>{{ scope.row.answerUser ? scope.row.answerUser.username : '未分配' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="state">
        <template slot-scope="scope">
          <div v-if="scope.row.state === 1" style="color:crimson;">未回答</div>
          <div v-else-if="scope.row.state === 2">未支付</div>
          <div v-else-if="scope.row.state === 3 && scope.row.subState === 1"><el-badge value="追问" class="item"><span>已支付</span></el-badge></div>
          <div v-else-if="scope.row.state === 3 && scope.row.subState === 2"><el-badge value="追答" class="item" type="primary"><span>已支付</span></el-badge></div>
          <div v-else-if="scope.row.state === 3">已支付</div>
          <div v-else-if="scope.row.state === 0">未付定金</div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}{{ scope.row.vipFreeQuery ? '(VIP免费咨询)' : '' }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="updateTime" label="更新日期" />
      <el-table-column
        v-if="checkPer(['admin','query:edit','query:del'])"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
            msg="确定删除吗,此操作不能撤销！"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import crudQuery from '@/api/system/query'
import crudUser from '@/api/system/user'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import CRUD, { crud, form, header, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import udOperation from '@crud/UD.operation'
import DateRangePicker from '@/components/DateRangePicker'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
const defaultForm = { id: null, name: null, isTop: '1', subCount: 0, pid: null, deptSort: 999, enabled: 'true' }
export default {
  name: 'Query',
  components: { rrOperation, udOperation, DateRangePicker, crudOperation, pagination },
  cruds() {
    return CRUD({ title: '文章', url: 'api/query', queryOnPresenterCreated: false, sort: ['state,asc', 'subState,asc', 'updateTime,desc'], crudMethod: { ...crudQuery }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 设置数据字典
  dicts: ['article_status', 'article_type'],
  data() {
    return {
      depts: [],
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        deptSort: [
          { required: true, message: '请输入序号', trigger: 'blur', type: 'number' }
        ]
      },
      permission: {
        edit: ['admin', 'query:edit'],
        del: ['admin', 'query:del'],
        dist: ['admin', 'query:dist']
      },
      enabledTypeOptions: [
        { key: '1', display_name: '未回答' },
        { key: '2', display_name: '未支付' },
        { key: '3', display_name: '已支付' }
      ],
      enabledSubStateOptions: [
        { key: '1', display_name: '追问未答' },
        { key: '2', display_name: '追问已答' }
      ],
      typeOptions: [
        { key: '0', display_name: '咨询' },
        { key: '1', display_name: '合作' }
      ],
      distributing: false,
      options: [],
      loading: false,
      userForm: {
        id: '',
        pushMessage: false,
        sendMessage: false
      }
    }
  },
  created() {
    this.crud.optShow = {
      add: false,
      edit: true,
      del: true,
      download: false,
      dist: true
    }
  },
  mounted() {
    if (this.$store.state.user.user.role.level === 1) {
      this.getClientUsers('')
    } else if (this.$store.state.user.user.role.level === 2) {
      this.query.answerUserId = this.$store.state.user.user.id
    }
    this.crud.refresh()
  },
  methods: {
    getClientUsers(query) {
      this.loading = true
      crudUser.getUserByRoleId({ roleId: 2, userName: query }).then(result => {
        this.loading = false
        this.options = result
      })
    },
    confirmDistribute() {
      crudQuery.distribute({
        ids: this.crud.selections.map(value => value.id),
        answerUserId: this.userForm.id,
        sendMessage: this.userForm.sendMessage,
        pushMessage: this.userForm.pushMessage
      }).then(result => {
        this.distributing = false
      })
    },
    toDistribute(selections) {
      this.distributing = true
    },
    getArticleDatas(tree, treeNode, resolve) {
      const params = { pid: tree.id }
      setTimeout(() => {
        crudQuery.getArticles(params).then(res => {
          resolve(res.content)
        })
      }, 100)
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      form.enabled = `${form.enabled}`
    },
    getSupDepts(id) {

    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内文章数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudQuery.getArticles({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    // 新增编辑前做的操作
    [CRUD.HOOK.beforeToCU](crud, form) {
      this.$router.push('/query/answer?id=' + form.id)
    },
    checkboxT() {
      return true
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control, ::v-deep .vue-treeselect__placeholder, ::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
.item {
  margin-top: 10px;
  margin-right: 40px;
}
</style>
